from decoders_func import Decoders
import config
import random
import obj_config


class Wrapper_decoders(Decoders):
    def dec_activation_name(self) -> str:
        if config.name_separation:
            vosk_str_no_tags = obj_config.obj_api.queue_voice_event_time_str_api()
            dec_name_lookup = self.dec_name_recognition(vosk_str_no_tags)
            if dec_name_lookup:
                config.speech_recognition_str_api_one = vosk_str_no_tags
                return vosk_str_no_tags
            else:
                return ""
        elif not config.name_separation:
            obj_config.communication_obj.turning_on_message("Скажите функцию")
            vosk_str_no_tags = obj_config.obj_api.queue_voice_event_time_str_api()
            if vosk_str_no_tags:
                config.speech_recognition_str_api_one = vosk_str_no_tags
                return vosk_str_no_tags
            else:
                return ""

    # ---------------
    # Вызов функции self.dec_function_search
    def dec_activation_fuck(self, name_or_func: str = "") -> list:
        if not name_or_func and not config.name_separation:
            name_or_func = obj_config.obj_api.queue_voice_str_api()
        elif name_or_func:
            pass
        func = self.dec_function_recognition_glav(name_or_func, "void")
        return func
        # Если слово в расп. речи совпало с импортированным декодером то вызываем self.dec_egg_decoders
        # return self.dec_egg_decoders(func, name_or_func)

    def dec_egg_decoders(self, list_name_decoders: list, vosk_str: str) -> list:
        # Дописать определение декодера меток по названию функций
        __list_decoder = []
        if list_name_decoders:
            for name_decoder in list_name_decoders:
                if name_decoder.find("egg_decoder") != -1:
                    obj_config.obj_import_egg.keys(name_decoder)
                    __list_decoder.append(
                        obj_config.obj_import_egg.import_func()(vosk_str)
                    )
                else:
                    __list_decoder.append(name_decoder)
            return __list_decoder
        else:
            return []

    def selection_file_params(self, list_titles, voice_str):
        # Баг
        if config.decoder_tags_vs_str == "tags":
            obj_config.communication_obj.messege("Скажите индекс")
            value = obj_config.obj_number_dec.number_activation_label([voice_str])[0]
            return value
        # Баг
        elif config.decoder_tags_vs_str == "int":
            obj_config.communication_obj.messege("Скажите название")
            return obj_config.decoders_obj.decoder_titles(voice_str, list_titles)
        else:
            obj_config.communication_obj.messege("Скажите название")
            return obj_config.decoders_obj.decoder_titles(voice_str, list_titles)

    def selection_file_decoders(self, list_titles) -> int:
        flag_name_index = False
        for x in list_titles:
            for b in config.dict_value_str_voice["dict_word"]:
                if b in x:
                    flag_name_index = True
        if flag_name_index:
            obj_config.communication_obj.messege("Скажите индекс")
            value = obj_config.obj_number_dec.one_int_index_number(
                [obj_config.obj_api.queue_voice_str_api()]
            )
            return value
        elif config.decoder_tags_vs_str == "int":
            obj_config.communication_obj.messege("Скажите индекс")
            value = obj_config.obj_number_dec.one_int_index_number(
                [obj_config.obj_api.queue_voice_str_api()]
            )
            return value
        elif config.decoder_tags_vs_str == "tags":
            obj_config.communication_obj.messege("Скажите название")
            return obj_config.decoders_obj.decoder_titles(
                obj_config.obj_api.queue_voice_str_api(), list_titles
            )
        else:
            rand = random.randint(1, 2)
            if rand == 1:
                obj_config.communication_obj.messege("Скажите индекс")
                value = obj_config.obj_number_dec.one_int_index_number(
                    [obj_config.obj_api.queue_voice_str_api()]
                )
                return value
            else:
                obj_config.communication_obj.messege("Скажите название")
                return obj_config.decoders_obj.decoder_titles(
                    obj_config.obj_api.queue_voice_str_api(), list_titles
                )

    def loop_call_func(self, funcs=""):
        # Функция нужна для того ,чтобы одной функции можно было каждый раз
        # задавать параметры
        menu_flag = ""
        if not funcs:
            obj_config.communication_obj.messege(
                "Циклическая вызов функций. Скажите функцию"
            )
            funcs = obj_config.wrapper_decoders_obj.dec_activation_fuck(
                obj_config.obj_api.queue_voice_str_api()
            )
        while "end" not in menu_flag:
            # Сделать время ожидания функции
            str_cmd = obj_config.obj_api.queue_voice_time_str_api()
            cmd = obj_config.wrapper_decoders_obj.dec_function_recognition(
                str_cmd, "loop_make"
            )
            if cmd:
                cmd = cmd[0]
                if cmd in config.cmds["loop_make"]:
                    menu_flag = cmd
                if ("pause" not in menu_flag) and ("return_tags" not in menu_flag):
                    if funcs:
                        obj_config.calls_funcs_obj.calls_cmd_no_spech_recogn(funcs)
                    else:
                        return "Функция не обнаружена"
                elif ("return_tags" in menu_flag):
                    for index, func in enumerate(funcs):
                        obj_config.communication_obj.messege(
                            f'Будет вызвана функция "{config.cmds_void[func]["word_list"][0]}"'
                        )
                elif ("clear" in menu_flag):
                    str_cmd = obj_config.obj_api.queue_voice_time_str_api()
                    funcs = obj_config.wrapper_decoders_obj.dec_activation_fuck(str_cmd)
                    if len(funcs) == 1:
                        obj_config.communication_obj.messege("Заданна новая функция")
                    elif len(funcs) > 1:
                        obj_config.communication_obj.messege("Заданны новые функции")
                    elif not funcs:
                        obj_config.communication_obj.messege("Список функций пуст")
                    else:
                        menu_flag = "end"
                else:
                    pass
        return "Завершение обработки функций"

    def decoder_rewind(self, list_cmd):
        # Обработка в цикле функции
        cmd_int = -1
        loop_make_flag = True
        cmd_make = ""
        while loop_make_flag:
            voice_str = obj_config.obj_api.queue_voice_str_api()
            cmd_make = obj_config.wrapper_decoders_obj.dec_function_recognition(
                voice_str, "list_message_enter_dict_cmds"
            )
            if not cmd_make:
                cmd_int = obj_config.wrapper_decoders_obj.selection_file_params(
                    list_cmd, voice_str
                )
            elif cmd_int != -1 or cmd_make:
                loop_make_flag = False
                cmd_make = ""
                cmd_int = 0
        return cmd_int, cmd_make

    def decoder_rewind_and_index(self, json_name_key):
        # Обработка в цикле функции

        loop_make_flag = True
        cmd_make = []
        while loop_make_flag:
            voice_str = obj_config.obj_api.queue_voice_str_api()
            cmd_make = obj_config.wrapper_decoders_obj.dec_function_recognition(
                voice_str, json_name_key
            )
            if cmd_make:
                cmd_make = cmd_make[0]
                loop_make_flag = False
        return cmd_make

    """
    def loop_func(self) -> dict:
        funcs_all = []
        menu_flag = ""
        funcs = []
        cmd = ""
        obj_config.communication_obj.messege("Циклическая обработка меток")
        while "end" not in menu_flag:
            str_cmd = obj_config.obj_api.queue_voice_str_api()


            if len(str_cmd)!=0:
                cmd = obj_config.wrapper_decoders_obj.dec_function_recognition(str_cmd, "loop_make")


            if (cmd in config.cmds["loop_make"]):
                menu_flag = cmd

            if ("pause" not in menu_flag) and ("return_tags" not in menu_flag) and ("add" in menu_flag):

                funcs = obj_config.decoders_obj.dec_function_recognition_glav(str_cmd, "void")
                funcs_all = funcs_all +funcs["value"]

            elif ("return_tags" in menu_flag) == True:
                obj_config.communication_obj.messege(" ".join(funcs_all))

            elif ("clear" in menu_flag)==True:

                funcs_all.clear()
                obj_config.communication_obj.messege("Функции очищены")

            else:
                pass

        return funcs

    """

    def dict_menu_mess(self, mess_dict):
        exit_flag = False
        list_keys = list(mess_dict.keys())
        index = 0
        len_list_key = len(list_keys)
        while not exit_flag:
            if index >= 0 and index < len_list_key and not exit_flag:
                key = list_keys[index]
                cat_mess = mess_dict[key]
                obj_config.communication_obj.message(f"Желаете прослушать {key}")
                permission_key = obj_config.obj_decoders.dec_function_recognition_keys(
                    obj_config.obj_api.queue_voice_str_api(), "other"
                )
                if permission_key == "yes":
                    key = list_keys[index]
                    text_mess = cat_mess
                    obj_config.communication_obj.message(text_mess)
                    index += 1
                elif permission_key == "back":
                    index -= 1
                    key = list_keys[index]
                    text_mess = cat_mess
                    obj_config.communication_obj.message(text_mess)
                elif permission_key == "forward":
                    index += 1
                    key = list_keys[index]
                    text_mess = cat_mess
                    obj_config.communication_obj.message(text_mess)
                elif permission_key == "metka_end":
                    exit_flag = True
                    break
                elif permission_key == "no":
                    exit_flag = True
                    break
                elif permission_key == "repeat":
                    pass
                else:
                    pass
            elif index < 0:
                index = 0
            elif index >= len(len_list_key):
                index = len_list_key - 1
        return ""

    def key_or_num(self, vois_str="", key_dict="other"):
        if not vois_str:
            vois_str = obj_config.obj_api.queue_voice_str_api()
        num = -1
        permission_key = ""
        permission_key = obj_config.obj_decoders.dec_function_recognition_keys(
            vois_str, key_dict
        )
        list_number = obj_config.obj_number_dec.number_activation_label([vois_str])
        if list_number:
            num = list_number[0]
        return (permission_key, num)
